package mymail;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;

public class DeleteMail {
	public Folder folder = null; // current folder
	public Folder[] folders = null;
	private String userName;

	@SuppressWarnings("deprecation")
	public boolean deleteOnClient(Message msg) throws Exception {
		String msgDetail = msg.getReceivedDate().toLocaleString()
				.replace(" ", "").replace(":", "").replace(",", "");

		File history = new File("./history/" + userName + "_deletedFile.txt");

		if (!history.exists()) {
			history.createNewFile();
		}

		FileWriter fstream = new FileWriter(history.getAbsolutePath(), true);
		BufferedWriter out = new BufferedWriter(fstream);
		out.write(msgDetail);
		out.newLine();
		out.close();

		return true;
	}

	public boolean deleteOnServer(Message msg) throws Exception {
		int mode = folder.getMode();
		if (folder.isOpen() && mode == Folder.READ_WRITE) {
			msg.setFlag(Flags.Flag.DELETED, true);
			folder.close(true);
			folder.open(mode);
		} else {
			return false;
		}
		return true;
	}

	public boolean delete(Message msg) throws Exception {
		int mode = folder.getMode();
		if (folder.isOpen() && mode == Folder.READ_WRITE) {
			deleteOnClient(msg);
			msg.setFlag(Flags.Flag.DELETED, true);
			folder.close(true);
			folder.open(mode);
		} else {
			return false;
		}
		return true;
	}

	@SuppressWarnings("deprecation")
	public boolean checkIfDeletedOnClient(Message msg) throws Exception {
		String msgDetail = msg.getReceivedDate().toLocaleString()
				.replace(" ", "").replace(":", "").replace(",", "");

		File history = new File("./history/" + userName + "_deletedFile.txt");

		if (history.exists()) {
			FileInputStream fstream = new FileInputStream(
					history.getAbsoluteFile());
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				if (msgDetail.equals(strLine)) {
					return true;
				}
			}
			in.close();
		}

		return false;
	}
}
